package com.dk.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

//    shiro权限拦截器是基于过滤器的,我们只机械的拦截是基于拦截器的
//    开启shiro的过滤器链 ShiroFilterFactoryBean : shiro过滤器的工厂实例类,专门用于shiro的过滤的

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSessionManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器,
        factoryBean.setSecurityManager(defaultWebSessionManager);
        /*
        * shiro常用过滤器
        * anon : 表示无需认证
        *  authc : 表示必须认证才能访问
        * perms : 表示当前权限需要每个权限
        *  */
        System.out.println("安全管理器");

//        对比springMVc,过滤器我们要添加一个shiro的过滤器
        Map<String , String> map = new LinkedHashMap<>();//hashMap是无序的,所以用linkHashMap
//        map.put("/shiro/select","anon");
        map.put("/admin/login","anon");
        map.put("/**/*.js","anon");
        map.put("/**/*.css","anon");
//        map.put("/admin/login","anon");
//        map.put("/index","anon");
//        map.put("/logout","logout");
//        map.put("/menu/getshow","perms[menushow]");
//        map.put("/role/getinsert","perms[role_add]");
        map.put("/**","authc");
        factoryBean.setLoginUrl("/toLogin");
//        factoryBean.setUnauthorizedUrl("/admin/unauthorized");
        factoryBean.setFilterChainDefinitionMap(map);
        return factoryBean;
    }

//创建安全管理对象
    @Bean
    public DefaultWebSecurityManager defaultWebSessionManager(@Autowired com.dk.shiro.LoginRealmConfig shiroRealmConfig){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealmConfig);
        return securityManager;
    }

    @Bean
    public com.dk.shiro.LoginRealmConfig shiroRealmConfig(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        com.dk.shiro.LoginRealmConfig config = new com.dk.shiro.LoginRealmConfig();
        config.setCredentialsMatcher(hashedCredentialsMatcher);
        return config;
    }

//    开启shiro密码加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密方式MD5
        matcher.setHashAlgorithmName("MD5");
        //设置加密次数
        matcher.setHashIterations(6);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

}
